/*
* time 2018-12-14
* */
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin // Webpack包文件分析器
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const vConsolePlugin = require('vconsole-webpack-plugin') // 引入 移动端模拟开发者工具 插件 （另：https://github.com/liriliri/eruda）
const px2rem = require('postcss-px2rem')
const path = require('path')
const glob = require('glob')

const resolve = (dir) => {
    return path.join(__dirname, dir)
}
const postcss = px2rem({
    remUnit: 32 // 基准大小 baseSize，需要和rem.js中相同
})

function addStyleResource(rule) {
    rule.use('style-resource')
        .loader('style-resources-loader')
        .options({
            patterns: [
                path.resolve(__dirname, 'src/styles/common.less'), // 需要全局导入的less
                // path.resolve(__dirname, 'src/styles/mixin.less'),
            ],
        })
}


//获取入口js和模板html
function getEntry(globPath) {
    let entries = {}, basename, tmp, pathname, appname
    glob.sync(globPath).forEach(function (entry) {
        basename = path.basename(entry, path.extname(entry))
        tmp = entry.split('/').splice(-3)
        pathname = basename // 正确输出js和html的路径
        appname = pathname.split('-')[0]
        entries[appname] = {entry: entry, template: 'public/index.html', filename: appname + '.html', tmp: tmp[1]}
    })
    return entries
}

let alljs = getEntry('./src/pages/**/*.js')
// const vConsole = process.env.NODE_ENV === "production" ? false : true
let vConsole
let isHash
if (process.env.VUE_APP_CURRENTMODE === 'stage' || process.env.VUE_APP_CURRENTMODE === 'local') {
    isHash = false
    vConsole = true
} else {
    vConsole = false
    isHash = true
}

module.exports = {
    publicPath: process.env.baseUrl,
    productionSourceMap: false,
    filenameHashing: isHash,
    outputDir: process.env.outputDir,
    chainWebpack: config => {
        config.module
            .rule('images')
            .use('url-loader')
            .tap(options => Object.assign(options, {limit: 500}))
        // 移除prefetch(告诉浏览器在页面加载完成后，利用空闲时间提前获取用户未来可能会访问的内容)
        // 移除preload(指定页面加载后很快会被用到的资源)
        Object.keys(alljs).forEach(entryName => {
            config.plugins.delete(`prefetch-${entryName.tmp}`)
            config.plugins.delete(`preload-${entryName.tmp}`)
        })
        const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
        types.forEach(type => addStyleResource(config.module.rule('less').oneOf(type)))
    },
    pages: alljs,
    
    configureWebpack: (config) => {
        // 入口文件
        // config.entry = ['babel-polyfill', './src/index.js']
        //别名
        config.resolve.alias = {
            '@': resolve('src'),
            '@assets': resolve('src/assets'),
            '@layouts': resolve('src/layouts'),
            '@pages': resolve('src/pages'),
            '@comp': resolve('src/components'),
            '@views': resolve('src/views'),
            '@api': resolve('src/api'),
            '@plug': resolve('src/plugins'),
            '@native': resolve('src/native'),
            '@utils': resolve('src/utils'),
            '@styles': resolve('src/styles'),
        }
        //打包分离
        config.optimization = {
            splitChunks: {
                cacheGroups: {
                    vendor: {
                        chunks: "all",
                        test: /node_modules/,
                        name: "chunk-vendors",
                        minChunks: 1,
                        maxInitialRequests: 5,
                        minSize: 0,
                        priority: 100,
                    },
                    /*common: {
						chunks:"all",
							test:/[\\/]src[\\/]js[\\/]/,
							name: "common",
							minChunks: 2,
							maxInitialRequests: 5,
							minSize: 0,
							priority:60
					}*/
                }
            }
        }
        // 生产and测试环境
        let pluginsPro = [
            // new BundleAnalyzerPlugin(), // Webpack包文件分析器(https://github.com/webpack-contrib/webpack-bundle-analyzer)
            /* new CompressionWebpackPlugin({
			   algorithm: 'gzip',
			   test: /\.js$|\.html$|\.css/,
			   threshold: 10240,
			   minRatio: 0.8
			 })*/
            new vConsolePlugin({  //移动端模拟开发者工具(https://github.com/diamont1001/vconsole-webpack-plugin  https://github.com/Tencent/vConsole)
                filter: [], // 需要过滤的入口文件
                enable: false // 发布代码前记得改回 false
            }),
        ]
        // 开发环境
        let pluginsDev = [
            new vConsolePlugin({  //移动端模拟开发者工具(https://github.com/diamont1001/vconsole-webpack-plugin  https://github.com/Tencent/vConsole)
                filter: [], // 需要过滤的入口文件
                enable: true // 发布代码前记得改回 false
            }),
        ]
        
        if (process.env.NODE_ENV === 'development') { // 为开发环境修改配置...
            config.plugins = [...config.plugins, ...pluginsDev]
        } else { // 为生产环境修改配置...process.env.NODE_ENV !== 'development'
            config.plugins = [...config.plugins, ...pluginsPro]
        }
    },
    devServer: {
        host: '192.168.0.63',
        port: 5555,
        https: false,
        open: false, // 配置自动启动浏览器
        hotOnly: true, // 热更新
        proxy: {
            '/web': {
                ws: false,
                // target: 'http://192.168.0.17:8884',  //龙哥
                target: 'http://192.168.0.98:8884',  //老杨
                // target: 'http://47.112.1.31',
                changeOrigin: true
            },
            '/movie': {
                target: 'https://api-m.mtime.cn/',
                changeOrigin: true,
                pathRewrite: {
                    '^/movie': ''
                }
            },
            '/ticket': {
                target: 'https://ticket-api-m.mtime.cn/movie/',
                changeOrigin: true,
                pathRewrite: {
                    '^/ticket': ''
                }
            },
            '/api': {
                target: 'http://localhost:3000/',
                changeOrigin: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        }
    },
    lintOnSave: false,
    css: {
        extract: true,
        loaderOptions: { // 向 CSS 相关的 loader 传递选项
            less: {
                javascriptEnabled: true
            },
           /* postcss: {
                plugins: [
                    postcss
                ]
            }*/
        }
    }
}
